
package com.shangsi.servletcontainer;

import com.shangsi.filter.UserFilter;
import com.shangsi.listener.UserListener;
import com.shangsi.service.HelloService;
import com.shangsi.servlet.UserServlet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.HandlesTypes;
import java.util.EnumSet;
import java.util.Set;

/**
 * servlet容器启动的时候
 * 次种方法可以进行一个加载比如第三方的组件类我们无法去修改其代码为其添加注解,所以可以在容器初始化中进行添加
 * @author dzd
 * @date 2021-12-12
 */
@HandlesTypes(value = {HelloService.class})
public class MyServletContainerInitializer implements ServletContainerInitializer {
    /**
     * 使用编码的时候给项目添加组件
     * 启动时候的方法
     * @param set 感兴趣的类(HandlesTypes中的类以及其子类)
     * @param servletContext 作用域
     * @throws ServletException ServletException
     */
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        System.out.println("MyServletContainerInitializer onStartup ...");
        for (Class<?> aClass : set) {
            System.out.println(aClass.getName());
        }
        //注册servlet组件
        ServletRegistration.Dynamic servlet = servletContext.addServlet("userServlet", new UserServlet());
        servlet.addMapping("/user");

        //注册listener
        servletContext.addListener(UserListener.class);
        //过滤器，过滤所有的请求
        FilterRegistration.Dynamic userFilter = servletContext.addFilter("userFilter", new UserFilter());
        userFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*");


    }
}
